package com.vnp.vchat.fragment;

import java.util.ArrayList;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.telpoo.frame.utils.Mlog;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.adapter.KhachhangAdapter;
import com.vnp.vchat.adapter.SourceAdapter;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.util.KeyboardHelper;
import com.vnp.vchat.util.Utils;
import com.vnp.vchat.version2.ChatNewActivity;

@SuppressLint("NewApi")
public class KhachhangScr extends Fragment implements OnTouchListener, OnClickListener{
	
	ListView  listKhachhang;
	KhachhangAdapter adapter;
	EditText edtSearch;
	ArrayList<ObjKhachhang> objKhachhangs = new ArrayList<ObjKhachhang>();
	ViewGroup main;
	ImageView btnClear;
	
	ImageButton btnSearch, btnCloseSearch, btnSettings;
	View seachView;
	TextView title;
	
	TextView titleOnline, txtSoluong;
	ImageView imgOnline;
	
	MySQLiteHelper db;
	private BroadcastReceiver mReceiver;
	
	//Animation topToDown;
	TextView txtNoSuplier;
	
	// check dang cuon hay khon
	boolean isScrolling = false;
	
	Dialog d;
	
	String sourceChoose = "";
	TextView txtTatca;
	ArrayList<String> listSr = new ArrayList<String>();
	
	ViewGroup llOnline;
	
	
	Handler mHandler = new Handler();
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		db = new MySQLiteHelper(getActivity());
	}
	
	
	ViewGroup viewGroup;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if(viewGroup==null) {
			viewGroup = (ViewGroup) inflater.inflate(R.layout.scr_khachhang, container, false);
		} else {
			((ViewGroup) viewGroup.getParent()).removeView(viewGroup);
		}
		main = (ViewGroup) viewGroup.findViewById(R.id.main);
		KeyboardHelper.setupUI(getActivity(), main);
		
		edtSearch = (EditText) viewGroup.findViewById(R.id.edt_search);
		
		//topToDown = AnimationUtils.loadAnimation(getActivity(), R.anim.top_to_down);
		
		title = (TextView) viewGroup.findViewById(R.id.title);
		title.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);
		seachView = viewGroup.findViewById(R.id.search_view);
		btnSearch = (ImageButton) viewGroup.findViewById(R.id.btn_search);
		btnSearch.setVisibility(View.INVISIBLE);
		btnCloseSearch = (ImageButton) viewGroup.findViewById(R.id.btn_close_search);
		btnCloseSearch.setVisibility(View.GONE);
		
		llOnline = (ViewGroup) viewGroup.findViewById(R.id.ll_online);
		
		btnSettings = (ImageButton) viewGroup.findViewById(R.id.btn_settings_khachhang);
		
		titleOnline = (TextView) viewGroup.findViewById(R.id.txt_title_online);
		txtSoluong = (TextView) viewGroup.findViewById(R.id.txt_soluong_online);
		imgOnline = (ImageView) viewGroup.findViewById(R.id.img_online);
		
		listKhachhang = (ListView) viewGroup.findViewById(R.id.list_khachhang);
		btnClear = (ImageView) viewGroup.findViewById(R.id.btn_clears);
		
		txtNoSuplier = (TextView) viewGroup.findViewById(R.id.txt_no_supplier);
		
		listSr = db.getSource();
		
		if (sourceChoose.equals("")){
			objKhachhangs = db.getAllKH(sourceChoose, true);
		} else {
			objKhachhangs = db.getAllKH(sourceChoose, false);
		}
		
//		setDataDemo();
		adapter = new KhachhangAdapter(getActivity(), objKhachhangs);
		listKhachhang.setAdapter(adapter);
		search();
		setData();
		init();
		setFont();
		
		recivedBroadcast();
		
		noSupplier();
		
		listKhachhang.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				MainPanelActivity.onGoto = true;
				Intent c = new Intent(getActivity(),ChatNewActivity.class);
				c.putExtra("khachhang", objKhachhangs.get(position));
				startActivity(c);
				getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
			}
		});
		
		listKhachhang.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == 0){
					isScrolling = false;
				} else {
					isScrolling = true;
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				
			}
		});
		return viewGroup;
	}
	
	
	private void setData() {
		txtSoluong.setText("("+ objKhachhangs.size()+ " người trực tuyến)");
	}
	
	private void noSupplier(){
		if (objKhachhangs.size() > 0){
			llOnline.setVisibility(View.VISIBLE);
			titleOnline.setText("Khách vãng lai");
			imgOnline.setVisibility(View.VISIBLE);
			btnSettings.setVisibility(View.VISIBLE);
			imgOnline.setVisibility(View.VISIBLE);
			txtNoSuplier.setVisibility(View.GONE);
			listKhachhang.setVisibility(View.VISIBLE);
		} else {
			llOnline.setVisibility(View.VISIBLE);
			titleOnline.setText("Đang theo dõi khách vãng lai...");
			imgOnline.setVisibility(View.GONE);
//			btnSettings.setVisibility(View.GONE);
			btnSearch.setVisibility(View.INVISIBLE);
			listKhachhang.setVisibility(View.GONE);
			txtNoSuplier.setVisibility(View.GONE);
		}
	}
	
	private void setFont() {
		edtSearch.setTypeface(Utils.getTypefaceRegular(getActivity()));
		titleOnline.setTypeface(Utils.getTypefaceRegular(getActivity()));
		txtSoluong.setTypeface(Utils.getTypefaceRegular(getActivity()));
		txtNoSuplier.setTypeface(Utils.getTypefaceRegular(getActivity()));
//		title.setTypeface(Utils.getTypefaceBlack(KhachhangActivity.this), Typeface.BOLD);
	}
	
	private void search() {
		edtSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().length() > 0){
					btnClear.setVisibility(View.VISIBLE);
				} else {
					btnClear.setVisibility(View.GONE);
				}
				String text = edtSearch.getText().toString().toLowerCase(Locale.getDefault());
				adapter.filter(text);
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	}
	private void init() {
		edtSearch.setOnTouchListener(this);
		btnClear.setOnClickListener(this);
		btnSearch.setOnTouchListener(this);
		btnCloseSearch.setOnTouchListener(this);
		btnSettings.setOnClickListener(this);
	}
	


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.edt_search:
			if (event.getAction() == MotionEvent.ACTION_UP){
				edtSearch.setCursorVisible(true);
			}
			break;
		case R.id.btn_search:
			if (event.getAction() == MotionEvent.ACTION_UP){
				showSearch();
			}
			break;
			
		case R.id.btn_close_search:
			if (event.getAction() == MotionEvent.ACTION_UP){
				closeSearch();
			}
			break;

		default:
			break;
		}
		return false;
	}


	 void showSearch(){
		btnSearch.setVisibility(View.INVISIBLE);
		seachView.setVisibility(View.VISIBLE);
		title.setVisibility(View.GONE);
		btnSettings.setVisibility(View.GONE);
		btnCloseSearch.setVisibility(View.VISIBLE);
		edtSearch.requestFocus();
		edtSearch.setCursorVisible(true);
		KeyboardHelper.displaySoftKeyboard(getActivity(), edtSearch);
	 }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_clears:
			edtSearch.setText("");
			break;
		case R.id.btn_search:
			break;
		case R.id.btn_close_search:
			break;
		case R.id.btn_settings_khachhang:
			showPopUp();
			break;

		default:
			break;
		}
	}
	
	private void recivedBroadcast(){
		 IntentFilter intentFilter = new IntentFilter();
		 intentFilter.addAction("com.app.vchat.REFRESH");
		    
		    mReceiver = new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, Intent intent) {
					
					
					getActivity().runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							showDulieu();
						}
					});
					Log.i("vChat", "Nhan duoc broadcast");
				}
			};
			
			// register
			//this.registerReceiver(mReceiver, intentFilter);
	}
	
	public void showDulieu(){
		if (sourceChoose.equals("")){
			objKhachhangs = db.getAllKH(sourceChoose, true);
		} else {
			objKhachhangs = db.getAllKH(sourceChoose, false);
		}
		
		Log.i("vChat", "OBJKH LOC: "+objKhachhangs.size());
		
		if (objKhachhangs.size() > 0){
			llOnline.setVisibility(View.VISIBLE);
			if (edtSearch.getVisibility() == View.VISIBLE){
				
			} else {
				btnSettings.setVisibility(View.VISIBLE);
				btnSearch.setVisibility(View.INVISIBLE);
			}
			
			txtNoSuplier.setVisibility(View.GONE);
			titleOnline.setText("Khách vãng lai");
			imgOnline.setVisibility(View.VISIBLE);
			listKhachhang.setVisibility(View.VISIBLE);
			setDulieuMoi();
			
			listSr = db.getSource();
			for (int j = 0; j < listSr.size(); j++) {
				Log.i("vChat", "List source: "+listSr.get(j));	
			}
		} else {
			llOnline.setVisibility(View.VISIBLE);
			titleOnline.setText("Đang theo dõi khách vãng lai...");
			imgOnline.setVisibility(View.GONE);
			btnSettings.setVisibility(View.VISIBLE);
			txtNoSuplier.setVisibility(View.GONE);
			btnSearch.setVisibility(View.INVISIBLE);
			listKhachhang.setVisibility(View.GONE);
		}
	}

	private void getSource(){
		for (int i = 0; i < objKhachhangs.size(); i++) {
			if (objKhachhangs.get(i).getTxtWebsite().equals(sourceChoose)){
				
			}
		}
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		//unregisterReceiver(mReceiver);
		/*mHandler.removeCallbacks(rc);
		mHandler.postDelayed(rc, 200);*/
	}
	
	
	
	@Override
	public void onPause() {
		super.onPause();
		/*mHandler.removeCallbacks(rc);
		mHandler.postDelayed(rc, 200);*/
	}
	
	void closeSearch(){
		KeyboardHelper.hideSoftKeyboard(getActivity());
		edtSearch.setText("");
		listKhachhang.setAdapter(adapter);
		btnSearch.setVisibility(View.INVISIBLE);
		seachView.setVisibility(View.GONE);
		title.setVisibility(View.VISIBLE);
		btnCloseSearch.setVisibility(View.GONE);
		btnSettings.setVisibility(View.VISIBLE);
	}


	private void setDulieuMoi(){
		adapter = new KhachhangAdapter(getActivity(), objKhachhangs);
		listKhachhang.setAdapter(adapter);
		if (isScrolling == true){
			
		} else { 	
			listKhachhang.setSelection(0);
		}
		
	}
	
	
	private void showPopUp(){
		final Dialog d = new Dialog(getActivity());
		d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		d.setContentView(R.layout.pop_up_filter_supplier);
		
		TextView txtNoSource = (TextView) d.findViewById(R.id.txt_no_source);
		TextView txtTitle = (TextView) d.findViewById(R.id.txt_title_loc);
		txtTatca = (TextView) d.findViewById(R.id.txt_tatca);
		
		ListView listSource = (ListView) d.findViewById(R.id.list_source);
		
		SourceAdapter adter = new SourceAdapter(getActivity(), listSr);
		listSource.setAdapter(adter);
		
		listSource.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> ad, View v, int position,
					long id) {
				sourceChoose = listSr.get(position);
				d.dismiss();
				showDulieu();
			}
			
		});
		
		txtTatca.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				d.dismiss();
				sourceChoose = "";
			}
		});
		
		Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();

		d.getWindow().setLayout((5 * width) / 7,
				((1 * height) / 3)); 
		
		d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		d.setCanceledOnTouchOutside(true);
		d.getWindow().setGravity(Gravity.CENTER);
		d.show();
		
		txtNoSource.setTypeface(Utils.getTypefaceRegular(getActivity()));
		txtTatca.setTypeface(Utils.getTypefaceRegular(getActivity()));
	}
	
	
}
